package com.share.cloudStorage.admin.service;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.jwt.JWT;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.share.cloudStorage.admin.dao.AdminDao;
import com.share.cloudStorage.admin.model.Admin;
import com.share.cloudStorage.admin.model.Params;
import com.share.cloudStorage.constant.Constants;
import com.share.cloudStorage.model.Result;
import com.share.cloudStorage.users.model.Users;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
@Transactional
public class AdminServiceImpl extends ServiceImpl<AdminDao, Admin> implements AdminService {
    @Autowired
    private AdminDao adminDao;

    @Override
    public Result loginHandel(Admin selAdmin, HttpServletResponse response, String password) {
        String spassword = DigestUtil.sha256Hex(password+ Constants.SALT);
        log.info("-----------------------------{}",spassword);
        //从redis查询密码
        log.info("{}",selAdmin==null);
        if (selAdmin==null){
            log.info("用户不存在");
            response.setStatus(500);
            return Result.fail("用户不存在");
        }
        if (selAdmin.getStatus().equals(1)){
            log.info("用户不存在");
            response.setStatus(500);
            return Result.fail("用户不存在");
        }

        if (!spassword.equals(selAdmin.getPassword())){
            log.info("用户密码错误");
            response.setStatus(500);
            return Result.fail("用户密码错误");
        }
        log.info("生成token");
        Date newDate = DateUtil.offset(DateUtil.date(),DateField.DAY_OF_YEAR, 7);
        // @formatter:off
        String token = JWT.create()
                .setExpiresAt(newDate)
                .setPayload(Constants.Admin_KEY, selAdmin.getUsername())
                .setKey(Constants.JWT_KEY.getBytes()).sign();
        Map<String, String> data = new HashMap<>();
        data.put(Constants.ADMIN_TOKEN_KEY,token);
        return Result.ok(data);
    }
    @Override
    public List<Users> adminsearch(Params params) {
        List<Users> userList = adminDao.adminsearch(params.getQueryParam(),params.getPageNum(),params.getPageSize());
        return userList;
    }
}
